package com.swak.metrics.impl;

import com.codahale.metrics.Counter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.codahale.metrics.Timer.Context;
import com.swak.meters.NamedMetrics;

public class NamedMetricsImpl extends AbstractMetrics implements NamedMetrics<Timer.Context> {

	private final String name;
	private final Timer time;
	private final Counter inuse;
	private final Counter count;

	/**
	 * 获得一个Name统计项
	 * 
	 * @param registry 监控实体
	 * @param name      需要监控的name
	 * @return 指标统计器
	 */
	public static NamedMetrics<Timer.Context> get(MetricRegistry registry, String name) {
		return new NamedMetricsImpl(registry, name);
	}

	protected NamedMetricsImpl(MetricRegistry registry, String name) {
		super(registry, name);
		this.name = name;
		this.time = this.timer("usage");
		this.count = this.counter("count");
		this.inuse = this.counter("in-use");
	}

	@Override
	public Timer.Context begin() {
		if (inuse != null) {
			inuse.inc();
		}
		if (time != null) {
			return time.time();
		}
		return null;
	}

	@Override
	public void end(Context t, boolean succeeded) {
		if (t != null) {
			t.stop();
		}
		if (inuse != null) {
			inuse.dec();
		}
		if (count != null) {
			count.inc();
		}
	}

	@Override
	public String name() {
		return name;
	}
}